#include "Entity.h"

namespace M7engine
{
Entity::Entity()
{
    id = -1;
    visible = true;
    active = true;
    image = NULL;
    setPosition(0, 0);
    direction = 0;
    width = 1;
    height = 1;
    rotation = 0;
    scale = 1;
    color = al_map_rgb(255, 255, 255);
    currentFrame = 0;
    totalFrames = 1;
    frameStart = 0;
    frameTimer = 0;
    animationColumns = 1;
    animationStartX = 0;
    animationStartY = 0;
    animationDir = 1;
}

Entity::~Entity()
{
    if (image != NULL)
    {
        al_destroy_bitmap(image);
    }
}

bool Entity::loadImage(const char *filename)
{
    if (image != NULL)
    {
        al_destroy_bitmap(image);
    }

    image = al_load_bitmap(filename);
    if (!image)
    {
        fprintf(stderr, "Failed to load bitmap: %s\n", filename);
        return false;
    }
    else
    {
        this->setSize(al_get_bitmap_width(image), al_get_bitmap_height(image));
        return true;
    }

}

void Entity::setImage(ALLEGRO_BITMAP *image)
{
    this->image = image;
    this->setSize(al_get_bitmap_width(image), al_get_bitmap_height(image));
}

void Entity::draw()
{
    if (image)
    {
        al_draw_tinted_scaled_rotated_bitmap(image, color, 0, 0, this->getX(), this->getY(), scale, scale, rotation, 0);
    }
}

void Entity::move()
{
    this->setX(this->getX() + this->velocity.getX());
    this->setY(this->getY() + this->velocity.getY());
}

void Entity::animate(float dt)
{
	if (frameTimer > 0.0f)
	{
		currentFrameTimer -= dt;

		if (currentFrameTimer < 0.0f)
		{
			while (currentFrameTimer < 0.0f)
			{
				if (currentFrame == totalFrames)
				{
					currentFrame = frameStart;
				}
				else
				{
					++currentFrame;
				}

				currentFrameTimer += frameTimer;
			}
		}
	}
}
}
